<?php
declare (strict_types = 1);

namespace app\common\model;

use app\common\facade\Target;

class Upgrade extends Base
{
   protected $name = 'upgrade';

    public function level()
    {
        return $this->hasOne(Level::class, 'id', 'level_id')->field('id,title');
    }

    public function getStatusAttr($value)
    {
        switch ($value) {
            case 1:
                return '待审核';
            case 2:
                return '已通过';
            case 3:
                return '已驳回';
            default:
                return '未知';
        }
    }

    public static function _save($param, $logs)
    {

        parent::startTrans();
        try {
            if (!isset($param['status'])) return ['code' => -1, 'msg' => '请选择审核类型'];

            $info = parent::find($param['id']);
            if (empty($info)) return ['code' => -1, 'msg' => '审核失败'];
            if ($info->getData('status') != 1) {
                return ['code' => -1, 'msg' => '此笔记录已审核，请勿重复审核！'];
            }
            if ($param['status'] == 2) {
                $msg = '通过激活申请，ID【' . $param['id'] . '】';
            } else {
                $msg = '驳回激活申请,ID【' . $param['id'] . '】';
            }

            $info->status = $param['status'];
            if ($param['status'] != 2) {
                $info->reject_msg = $param['reject_msg'];
            }
            $info->admin_id = $logs['admin']->id;
            $info->admin_name = $logs['admin']->admin_name;
            $info->confirm_time = time();
            $info->save();

            $level = Level::find($info->level_id);
            $user = User::find($info->uid);
            $user->level_id = $info->level_id;
            $user->is_active = 2;
            $user->active_time = time();
            $user->mature_time = time()+31536000;
            $user->activation = $level->activation;
            $user->commission = $level->commission;
            $user->save();

            User::where('id', $user->id)->inc('my_total', (float)$level->amount)->update();//个人业绩增加
            Relation::renewTeamTotal($level->amount,$user->id);//更新团队业绩
            User::activation_quicken($user->id);//推荐释放
            Target::Account()
                ->basics($user->id, 'coupon', $level->coupon, '激活赠送', '+')
                ->createNormal($user->id);
            Logs::adds($msg, $logs['admin']->id, $logs['admin']->admin_name);
            parent::commit();
            return ['code' => 1, 'msg' => '已审核'];

        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
